package user

import (
	"context"
	"strconv"
	"time"

	"mall/common/cryptx"
	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	// "mall/service/backend/common/utils/encrypt"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// User management
func (l *CreateUserLogic) CreateUser(in *backend.UserInfo) (*backend.BaseUUIDResp, error) {
	salt, err := cryptx.GenerateRandomHexString(16)
	if err != nil {
		return nil, errorx.NewInternalError("common.encryptError")
	}

	var user model.SysUser
	if in.Username != nil {
		user.Username = *in.Username

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysUserColumns.Username] = map[string][]any{
			"equalTo": []any{*in.Username},
		}
		filterMap[model.SysUserColumns.Status] = map[string][]any{
			"equalTo": []any{globalkey.StatusEnabled},
		}
		_, count, err := l.svcCtx.SysUser.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("user.usernameAlreadyExists")
		}
	}
	user.Salt = salt
	if in.Password != nil {
		user.Password = cryptx.EncryptPasswordWithSalt(*in.Password, salt)
	}
	if in.Nickname != nil {
		user.Nickname = *in.Nickname
	}
	if in.Email != nil && len(*in.Email) > 0 {
		user.Email = *in.Email

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysUserColumns.Email] = map[string][]any{
			"equalTo": []any{*in.Email},
		}
		filterMap[model.SysUserColumns.Status] = map[string][]any{
			"equalTo": []any{globalkey.StatusEnabled},
		}
		_, count, err := l.svcCtx.SysUser.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("user.emailAlreadyExists")
		}
	}
	if in.Mobile != nil && len(*in.Mobile) > 0 {
		user.Mobile = *in.Mobile

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysUserColumns.Mobile] = map[string][]any{
			"equalTo": []any{*in.Mobile},
		}
		filterMap[model.SysUserColumns.Status] = map[string][]any{
			"equalTo": []any{globalkey.StatusEnabled},
		}
		_, count, err := l.svcCtx.SysUser.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("user.mobileAlreadyExists")
		}
	}
	if in.Avatar != nil {
		user.Avatar = *in.Avatar
	}
	if in.HomePath != nil {
		user.HomePath = *in.HomePath
	}
	if in.Description != nil {
		user.Description = *in.Description
	}
	if in.DepartmentId != nil {
		user.DepartmentID = *in.DepartmentId
	}
	if in.Status != nil {
		user.Status = uint8(*in.Status)
	} else {
		user.Status = uint8(globalkey.StatusEnabled)
	}
	now := time.Now()
	user.CreatedAt = now
	user.UpdatedAt = now
	err = l.svcCtx.SysUser.Insert(l.ctx, nil, &user, &model.SysUserRel{
		RoleIds:     in.RoleIds,
		PositionIds: in.PositionIds,
	})
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseUUIDResp{
		Id:  strconv.FormatInt(int64(user.ID), 10),
		Msg: i18n.CreateSuccess,
	}, nil
}
